package com.rtu.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.rtu.dao.IWaterGatherDataDao;
import com.rtu.dao.IWaterStationDao;
import com.rtu.domain.WaterStation;
import com.rtu.dto.QueryStationDto;
import com.rtu.dto.WaterStationResponse;
import com.rtu.service.IWaterStationService;

@Service
public class WaterStationServiceImpl implements IWaterStationService{
	
	@Resource
	private IWaterStationDao waterStationDao;
	
	@Resource
	private IWaterGatherDataDao waterGatherDataDao;

	@Override
	public Map query(QueryStationDto dto) {
        Map map = new HashedMap();
        List<WaterStationResponse> list = new ArrayList<WaterStationResponse>();
        Integer count = waterStationDao.count();
        if (count == 0) {
            map.put("totalPage",0);
            map.put("totalCount",0);
        } else {
            int totalPage = (count % dto.getPageRowCount() == 0) ? count / dto.getPageRowCount() : count / dto.getPageRowCount() + 1;
            dto.setStart((dto.getPage() - 1) * dto.getPageRowCount());
            list = waterStationDao.query(dto);
            for(WaterStationResponse r : list) {
            	if(StringUtils.isNotBlank(r.getCalculationFormula())) {
            		WaterStation waterStation = new WaterStation();
            		waterStation.setCalculationFormula(r.getCalculationFormula());
            		waterStation.setId(r.getId());
                	r.setCurrentWaterLevel(waterGatherDataDao.queryData(waterStation));
            	}
            }
            map.put("totalPage",totalPage);
            map.put("totalCount",count);
        }
        map.put("pageRowCount", dto.getPageRowCount());
        map.put("page",dto.getPage());
        map.put("list",list);
        return map;
	}

	@Override
	public Map queryStationById(int id) {
		Map map = new HashedMap();
		WaterStation station = waterStationDao.queryById(id);
		map.put("station", station);
		return map;
	}

	@Override
	public int updateStation(WaterStation station) {
		return waterStationDao.updateStation(station);
	}

	@Override
	public int insertStation(WaterStation station) {
		return waterStationDao.insertStation(station);
	}

}
